//
//  BackgroundView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/7/16.
//

import SwiftUI
import Kingfisher


struct BackgroundView: View {
    var url: String? = nil
    @EnvironmentObject var viewModel: BackgroundViewModel
    var isMain = false

    var body: some View {
        ZStack {
            let fullUrl = viewModel.backgroundUrl
            if url?.isEmpty == false {
                getView(url: url)
            } else if fullUrl?.isEmpty == false {
                getView(url: fullUrl)
            } else if isMain {
                //没有背景的，则设置渐变
                Color.clear
                    .background(
                        LinearGradient(
                            //浅色是0.1，深色0.05。跟安卓的0.2跟0.1又差别
                            gradient: Gradient(colors: [ themeManager.themeColor.opacity(themeManager.themeColor.isLightColor() ? 0.2 : 0.1), .clear, .clear]),
                            startPoint: .topTrailing,
                            endPoint: .bottomLeading
                        )
                    )
            }
        }.onChange(of: viewModel.backgroundUrl) { newValue in
            updateTabBarAppearance(url: newValue)
        }.onChange(of: url) { newValue in  // 监听 url 的变化
            updateTabBarAppearance(url: newValue)
        }
    }
    
    //更新tabBar主题
    private func updateTabBarAppearance(url: String?) {
        showLog("更新tabBar主题$updateTabBarAppearance")
        if ((url ?? "")?.isEmpty == false)  {
            TabBarUtils.updateTabBarAppearance(true)
        } else {
            TabBarUtils.updateTabBarAppearance(false)
        }
    }
    
    func getView(url : String?) -> some View {
        GeometryReader { geometry in
            KFImage(URL(string: url.formatCdn()))
                .resizable()
                .aspectRatio(contentMode: .fill)
            //                .scaledToFit()
                .frame(width: geometry.size.width, height: geometry.size.height)
                .contentShape(Rectangle()) // 定义内容形状
                .clipped()
        }.edgesIgnoringSafeArea(.all) // 忽略安全区域，延伸到全屏
    }
}

var backgroundManager = BackgroundViewModel()

class BackgroundViewModel : BaseViewModel {
    @Published var backgroundUrl : String? = nil
    func setBackground(_ url : String?) {
        showLog("更新tabBar主题$setBackground")
        backgroundUrl = url
    }
    
    func isBg() -> Bool {
        return backgroundUrl?.isEmpty == false
    }
    
}

extension View {
    //全局控制背景透明
    func opacityBg(_ minValue : Double = 0) -> some View {
        self.opacity(backgroundManager.isBg() ? minValue : 1)
    }
    
    //单界面控制
    func opacityBg(isBg : Bool,_ minValue : Double = 0) -> some View {
        self.opacity(isBg ? minValue : 1)
    }
}

extension Color {
    //全局控制背景透明
    func opacityBg(_ minValue : Double = 0) -> Color {
        self.opacity(backgroundManager.isBg() ? minValue : 1)
    }
    //单界面控制
    func opacityBg(isBg : Bool,_ minValue : Double = 0) -> Color {
        self.opacity(isBg ? minValue : 1)
    }
}

extension UIColor {
    /// 判断颜色是否为浅色
    /// - Returns: 如果是浅色返回 true，否则返回 false
    func isLightColor() -> Bool {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        
        // 获取 RGB 分量值（0.0-1.0 范围）
        getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        
        // 转换为 0-255 范围
        let red255 = red * 255
        let green255 = green * 255
        let blue255 = blue * 255
        
        // 自定义权重计算亮度，降低绿色权重
        let luminance = 0.4 * red255 + 0.4 * green255 + 0.2 * blue255
        
        // 亮度大于 128 视为浅色
        let isLight = luminance > 128
        
        // 输出日志（在实际项目中可根据需要保留或删除）
        showLog("test: 亮度值：\(luminance)")
        showLog("test: 是否为浅颜色：\(isLight)")
        
        return isLight
    }
}

// 如果需要直接在 SwiftUI 的 Color 上使用，可以再添加这个扩展
extension Color {
    func isLightColor() -> Bool {
        return UIColor(self).isLightColor()
    }
}

//#Preview {
//    BackgroundView()
//}
